# Copyright 2010 Mikko Rantanen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from time import time
import stat
import os
import re
import logging

import fsentry

class Directory(fsentry.FSEntry):
    """
        Abstract base class for all directory-like objects such as
        views, virtual folders and traditional folders.
    """

    def __init__(self, parent, iteminfo):
        fsentry.FSEntry.__init__(self, parent, iteminfo)
        self.contents = None

        # Directories have two links. Itself and the previous one.
        self.st_nlink = 2

        # Kinda default directory size.
        self.st_size = 4096

        # Temporary till we figure out smarter defaults.
        self.st_mode = stat.S_IFDIR | 0755
        self.st_ino = 0
        self.st_dev = 0
        self.st_uid = os.getuid()
        self.st_gid = os.getgid()
        self.st_atime = int(time())
        self.st_mtime = self.st_atime
        self.st_ctime = self.st_atime

    def get_resource(self):
        # CACHEABLE: Might be called often. String operations and subrecursion
        return self.get_conn().resource('views' + self.get_urlpath() + '/folders')

    def get_contents(self):
        # CACHEABLE: Called all the time AND performs rest calls.
        contents = self.get_resource().get()
        self.contents = map(lambda item: fsentry.constructtype(self, item), contents['Items'])
        return self.contents

    def get_child(self, path):

        m = re.match('/(?P<immediate>[^/]*)(?P<remaining>/.*)?', path)
        assert m, 'Path is in invalid format: %s' % path

        if not self.contents:
            self.contents = self.get_contents()

        children = filter(lambda c: c.get_name() == m.group('immediate'), self.contents)
        if len(children) == 0:
            return None
            
        child = children[0]

        if m.group('remaining'):
            return child.get_child(m.group('remaining'))
        else:
            return child


